<?php	

class LoginController extends Controller
{
	const LEAVE_GAME = "leave";

	public function DoControll()
	{
		$this->Title( "Login" );

		require_once 'lib/Validation.php';
		$valid = new Validation();

		// If trying to logout, do it.
		if( $this->view->TriedToLogout() )
		{
			$this->model->DoLogout();
			header( "Location: index.php" );
		}
		
		// Tried to login.
		if( $this->view->TriedToLogin() )
		{
			// Validate username/password.
			if( $valid->IsValidUsername( $this->view->GetUsername() ) 
				&& $valid->IsValidPassword( $this->view->GetPassword() ) )
			{
				
				if( !$this->model->DoLogin( $this->view->GetUsername(), $this->view->GetPassword() ) )
				{
					$this->view->Error( 'Login attempt failed.' );
				}
				else
				{
					header( "Location: index.php" );
					//skapar cookie som används till push-funktionen för när spelare joinat ett spel
					setcookie("userid", Auth::GetUser()->GetID());
				}
			}
			else
			{
				// Either username or password doesnt validate.
				$this->view->Error( 'Invalid username or password.' );
			}
		}
		
		$this->view->DoLoginBox();
		
		$this->view->PrintErrors( '<p class="error"><span>Error :(</span> _ERROR_</p>' . "\r\n" );
		$this->view->PrintMessages( '<p class="message"><span>Success \o/</span> _MESSAGE_</p>' . "\r\n" );
	}
}
